package leetcode;

/**
 * @author yinlei
 * @date 2018/6/19
 * @since 1.0.0
 */
public class N006ZigZagConversion {

    public static void main(String[] args) {

        System.out.println(convert("PAYPALISHIRING", 4));
        System.out.println(convert("A", 1));
    }

    static public String convert(String s, int numRows) {

        if (numRows < 2) return s;

        int length = s.length();
        char[] chars = s.toCharArray();

        int one = (numRows - 1) * 2;
        int total = (int) Math.ceil(Double.valueOf(length) / one);

        StringBuffer sb = new StringBuffer(length);

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < total; j++) {
                int offset = j * one;
                int start = offset + i;
                if (start >= length) continue;

                sb.append(chars[start]);
                int next = one - i;
                if (next >= numRows && next < one && (offset + next) < length) {
                    sb.append(chars[offset + next]);
                }
            }
        }

        return sb.toString();
    }
}
